<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage>
      <div>
        <n-form ref="form"
            :model="searchCondition"
            label-placement="left"
            label-align="right"
            label-width="80px"
            :show-require-mark="false">
          <div>
            <div class="grid md:flex md:flex-wrap md:gap-x-1">
              <n-form-item>
                <label style="width: 120px;">上一级分类名称：</label>
                <n-input style="width: 170px;" v-model:value="searchCondition.parentCategoryName" placeholder="输入父级分类名称" clearable/>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                <label style="width: 70px;">分类名称：</label>
                <n-input style="width: 170px;" v-model:value="searchCondition.name" placeholder="输入当前分类名称" clearable/>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                <label style="width: 50px;">创建人:</label>
                <n-select v-model:value="searchCondition.adminId" :options="admins" />
              </n-form-item>
              <n-form-item  style="margin-left: 10px">
                <n-button type="primary" @click="searchByCondition">筛选</n-button>
              </n-form-item>
              <n-form-item  style="margin-left: 10px">
                <n-button type="primary" @click="showForm = true">添加分类</n-button>
              </n-form-item>
              <n-form-item  style="margin-left: 10px">
                <n-button type="error" @click="deleteSelectProductCategories">批量删除</n-button>
              </n-form-item>
              <n-form-item  style="margin-left: 10px">
                <n-button type="primary" @click="exportListInfo">导出</n-button>
              </n-form-item>
            </div>
          </div>
          </n-form>
      </div>
      <AddCategoryForm :option="option" @update-page="searchByCondition" :show="showForm" :onClose="handleClose" />
      <UpdateProductCategory
          @update-page="searchByCondition"
          :show1="showForm1"
          :onClose="handleClose"
          :productCategory="currentCategory"
          :optipn="option"
      />
      <n-data-table
          remote
          :single-line="false"
          ref="table"
          :columns="columns"
          :data="categoryList"
          :loading="loading"
          :pagination="paginationReactive"
          :row-key="rowKey"
          :scroll-x="900"
          @update:checked-row-keys="handleCheck"
      />
    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import CategoryActions from './components/category-actions.vue';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import AddCategoryForm from './components/category-add.vue';
import {NButton} from 'naive-ui'
import UpdateProductCategory from './components/category-edit.vue'

const showForm = ref(false);
const showForm1 = ref(false);
const handleClose = () => {
  showForm.value = false;
  showForm1.value = false;
};
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const categoryList = ref([])
const checkedRowKeysRef = ref([]);
const option = ref([
])
const currentCategory = ref(null);
const searchCondition = ref({
  adminId: -1,
  parentCategoryName: "",
  name: ""
});
const admins = ref([])
admins.value.push({
  label:'全部',
  value:-1,
})
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 60,
  },
  {
    key: 'id',
    title: '分类编号',
    width: 70,
  },
  {
    key: 'parentCategoryName',
    title: '所属分类',
    width: 100,
    render(row) {
      if(row["parentCategoryId"] === null) {
        return "无"
      }
      return row["parentCategoryName"]
    }
  },
  {
    key: 'name',
    title: '分类名称',
    width: 100,
  },
  {
    key: 'adminName',
    title: '创建人',
    width:100,
  },
  {
    key: 'createTime',
    title: '创建时间',
    width: 100,
    align:'left',
  },
  {
    key: 'operation',
    title: '操作',
    width: 100,
    render(row) {
      return h(
        CategoryActions,
        {
          onClickDelete: () => onDeleteProductCategory(row),
          onClickEdit: () => onEditProductCategory(row),
        }
      );
    }
  },
]
let total = 0
const paginationReactive = reactive({
  page: 1,
  pageSize: 20,
  showSizePicker: true,
  pageSizes: [20, 50, 100],
  itemCount:0,
  prefix: () => {
    return '查询出 ' + total + '条记录';
  },
  onChange: (page) => {
    paginationReactive.page = page;
    queryByPage()
  },
  onUpdatePageSize: (pageSize) => {
    paginationReactive.pageSize = pageSize;
    paginationReactive.page = 1;
    queryByPage()
  }
});
const handleCheck = (rowKeys) => {
  checkedRowKeysRef.value = rowKeys;
}
const deleteSelectProductCategories = () => {
  if(checkedRowKeysRef.value.length <= 0) {
    $message.error("当前并未选择产品分类！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选产品分类？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      loading.value = true
      try {
        const res = await api.deleteProductCategories({params:{ids}})
        if(res.code === 200) {
          $message.success("删除所选产品分类成功！")
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选产品分类失败！")
      }finally{
        loading.value = false
      }
    },
  })
}
const searchByCondition = async () => {
  loading.value = true
  try {
    paginationReactive.page = 1;
    const res = await api.findPageProductCategory({
      params: {
        adminId: searchCondition.value.adminId.toString(),
        parentCategoryName: searchCondition.value.parentCategoryName,
        name: searchCondition.value.name,
        pageNum: paginationReactive.page,
        pageSize: paginationReactive.pageSize,
      }
    })
    if(res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
      categoryList.value = res.data.records.map((item,i)=>{
        return {...item,
          colId: baseCount + i + 1,
        }
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("查询产品失败！")
  }finally{
    loading.value = false
  }
}
const exportListInfo = async () => {
  const res = await api.exportProductCategoryList({
      adminId: searchCondition.value.adminId.toString(),
      parentCategoryName: searchCondition.value.parentCategoryName,
      name: searchCondition.value.name,
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if(contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
  if(window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else{
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.download= fileName;
    elink.style.display ="none"
    elink.href  = window.URL.createObjectURL(blob)
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const onDeleteProductCategory = async (productCategory) => {
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前产品分类？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const {id} = productCategory
      loading.value = true
      try {
        const res = await api.deleteProductCategory({id})
        if(res.code === 200) {
          $message.success("删除产品分类成功！")
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除产品分类失败！")
      }finally{
        loading.value = false
      }
    }
  })
}
const onEditProductCategory = async (productCategory) => {
  const {id} = productCategory
  showForm1.value=true;
  currentCategory.value=productCategory
}
const queryByPage = async () => {
  loading.value = true
  try {
    const res = await api.findPageProductCategory(
        {
            params:{
                pageNum:paginationReactive.page,
                pageSize:paginationReactive.pageSize,
            }
        })
    if(res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
      categoryList.value = res.data.records.map((item,i)=>{
        return {...item,
          colId: baseCount + i + 1,
        }
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取产品失败！")
  }finally{
    loading.value = false
  }
}
const queryAllProductCategory = async  () => {
  try {
    const res = await api.findAllProductCategory()
    if(res.code === 200) {
      // 调用函数生成n-cascader的options
      convertToCascaderOptions(res.data);
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取产品失败！")
  }finally{
    loading.value = false
  }
}
const queryAdminList = async () => {
  loading.value = true
  try {
    const res = await api.findAllAdmin()
    if(res.code === 200) {
      res.data.map((item)=>{
        admins.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取管理员信息失败！")
  }finally{
    loading.value = false
  }
}
const convertToCascaderOptions = (flatData) => {
  const idNodeMap = {}; // 用于映射id到对应的节点对象
  const opt = []; // 最终生成的级联选择器数据
  // 首先，将所有的数据节点放到一个映射表中，方便后续通过ID快速查找
  flatData.forEach(node => {
    idNodeMap[node.id] = { ...node, children: [] };
  });
  // 构建树形结构
  Object.values(idNodeMap).forEach(node => {
    if (node.parentCategoryId === null) {
      // 如果parentId为null，则该节点是根节点
      opt.push(node);
    } else {
      // 否则，将该节点添加到其父节点的children数组中
      const parentNode = idNodeMap[node.parentCategoryId];
      if (parentNode) {
        parentNode.children.push(node);
      }
    }
  });
  console.log(opt)
  // 遍历并转换所有根节点
  option.value = opt.map(node=>{
    return traverse(node)
  });
}
// 转换数据结构为n-cascader所接受的格式（将name和parentName转换为label，并移除不必要的字段）
const traverse = (node) => {
  const { id, name, children } = node;
  // 如果children数组为空，则不返回children字段
  const processedNode = {
    value: id.toString(),
    label: name,
    ...(children.length > 0 ? { children: children.map(child => traverse(child)) } : {})
  };
  return processedNode;
};
// 使用optionsForNCascader作为n-cascader的options
const rowKey = (rowData) => {
  return rowData.id
}
onMounted(()=>{
  queryAdminList()
  queryAllProductCategory()
  queryByPage()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
  text-align: center;

}
:deep(.n-select) {
  width: 120px !important;
}

:deep(.two-line-description) {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 控制显示的行数 */
  overflow: hidden;
}
</style>
